<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="物料编码">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.dropDownData" @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar style="float: right" :items="['查询', '新增', '删除', '导出']" @add="addHandler" @del="deleteHandler"
            @select="selectHandler" @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
          :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size @change="PageSize"
      @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
      :current="pagination.page" />
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="500"
      :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
      @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="110px" label="开头工艺" field="foremanTechnology"
            :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '开头工艺必填' }]">
            <a-select popup-container="html"  class="bacClass" placeholder="" v-model="dataForm.foremanTechnology" @focus="focusSel2"
              @search="handleSearch2" :loading2="loading2" allow-clear>
              <a-option v-for="item in pageData.bgNameList" :value="item">
                {{ item }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="110px" label="物料名称" field="materialName" :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '物料名称必填' }]">
            <a-select popup-container="html"  placeholder="选择物料名称" v-model="dataForm.materialName" @focus="selCxAll(dataForm.materialName)"
              @change="wlChange" @search="selCxAll($event)" allow-search allow-clear class="bacClass">
              <a-option v-for="item in pageData.CodeNameList" :value="item['materialName']">
                {{ item['materialName'] }}
              </a-option>
            </a-select>
            <!-- <a-select popup-container="html" 
              :style="{ width: '320px' }"
              :loading="loading"
              placeholder="选择物料名称"
              multiple
              @search="handleSearch"
              :filter-option="true"
              class="bacClass"
              v-model="dataForm.materialName"
            >
              <a-option
                v-for="item of pageData.CodeNameList"
                :value="item['materialName']"
                :key="item['id']"
                >{{ item['materialName'] }}</a-option
              >
            </a-select> -->
          </a-form-item>
          <a-form-item label-col-flex="110px" label="物料编码" field="stockNumber">
            <a-input v-model="dataForm.stockNumber" disabled></a-input>
          </a-form-item>

          <a-form-item label-col-flex="110px" label="是否优先">
            <a-checkbox v-model="dataForm.priorityOrNot"> </a-checkbox>
          </a-form-item>
          <a-form-item label-col-flex="110px" label="最小值" field="minValues" :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '最小值必填' }]">
            <a-input-number class="bacClass" placeholder=" " :precision="1" v-model="dataForm.minValues"
              @change="minChange" />
          </a-form-item>
          <a-form-item label-col-flex="110px" label="最大值" field="maxValues" :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '最大值必填' }]">
            <a-input-number class="bacClass" placeholder=" " :precision="1" v-model="dataForm.maxValues"
              @change="maxChange" />
          </a-form-item>
          <a-form-item label-col-flex="110px" label="HAC酸性用量" field="hACacidity" :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: 'HAC酸性用量必填' }]">
            <a-input-number class="bacClass" placeholder=" " :precision="1" v-model="dataForm.hACacidity"
              @change="hacChange" />
          </a-form-item>
          <a-form-item label-col-flex="110px" label="备注" field="remark">
            <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear show-word-limit />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from '@/api/paging'
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { AnyARecord } from 'dns'

import { localeText } from '@/api/aggridZw'
import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { messageConfig } from 'element-plus'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface BrandInfo {
  id: any
  remark: any
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  deleteState: any
  obsoleteState: any
  stepNo: any
  materialName: any
  materialCode: any
  foremanTechnology: any
  priorityOrNot: any
  minValues: any
  maxValues: any
  hACacidity: any
  stockNumber: any
}

export default {
  name: 'FormulationMaterials',
  setup() {
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    //查询方法
    function doRefresh() {
      pageData.pageLoading = true
      // updateGridState01()
      post({
        url: '/pdm/formulaDose/selectPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: '0',
          stockNumber: pageData.dropDownData,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            gridOption.value.setRowData(data.list)

            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    //物料名称
    const wlmcFocus = () => {
      if (dataForm.stockNumber == '') {
        dataForm.materialName = ''
        Message.error('请先选择物料编码')
        return
      } else {
        post({
          url: '/purchase/MaterialInfo/getList',
          data: {
            materialCode: dataForm.stockNumber,
          },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.CodeNameList = data
          }
        })
      }
    }
    const wlChange = (val: any) => {
      console.log(val)
      let list = pageData.CodeNameList.filter((item: { materialName: string }) => {
        return item.materialName == val
      })
      dataForm.stockNumber = list[0]['materialCode']
      //   dataForm.id = list[0]['id']
      //   if (dataForm.materialName == '') {
      //     dataForm.stockNumber = ''
      //   }
      //   post({
      //     url: '/purchase/MaterialInfo/getList',
      //     data: {
      //       materialCode: dataForm.stockNumber,
      //     },
      //   }).then(({ data, code }: any) => {
      //     if (code === 200) {
      //       pageData.CodeNameList = data
      //       let list = pageData.CodeNameList.filter(function (o: any) {
      //         return o['materialCode'] == val
      //       })
      //       dataForm.materialName = list[0]['materialName']
      //     }
      //   })
    }
    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '序号',
        key: 'id',
        dataIndex: 'id',
        width: 160,
      },
      {
        title: '开头工艺',
        key: 'foremanTechnology',
        dataIndex: 'foremanTechnology',
        width: 160,
      },
      {
        title: '物料编码',
        key: 'stockNumber',
        dataIndex: 'stockNumber',
        width: 160,
      },
      {
        title: '物料名称',
        key: 'materialName',
        dataIndex: 'materialName',
        width: 160,
      },
      {
        title: '是否优先',
        key: 'priorityOrNot',
        dataIndex: 'priorityOrNot',
        slotName: 'priorityOrNot',
        width: 160,
      },
      {
        title: '最小值',
        key: 'minValues',
        dataIndex: 'minValues',
        width: 160,
      },
      {
        title: '最大值',
        key: 'maxValues',
        dataIndex: 'maxValues',
        width: 160,
      },
      {
        title: 'HAC酸性用量',
        key: 'hACacidity',
        dataIndex: 'hACacidity',
        width: 160,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 160,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 160,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 160,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 160,
        fixed: 'right',
      },
    ])
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
          setup(props: any) {
            console.log(props)

            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
            }
          },
        }
      }
      if (o.slotName === 'priorityOrNot') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 100
        obj['cellRenderer'] = {
          template: `<a-checkbox v-model="val" disabled></a-checkbox>`,
          setup(props: any) {
            let val = ref()
            val.value = props.params.data.priorityOrNot == 0 ? false : true
            return {
              val,
            }
          },
        }
      }
      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 60,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 60,
        maxWidth: 60,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      wlList: []
      isLxs: boolean
      CodeNameList: []
      bgNameList: any[]
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增配方用料',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      wlList: [],
      isLxs: false,
      CodeNameList: [],
      bgNameList: [],
    })

    interface gcType {
      id: any
      company: any
    }
    //下拉数据 物料名称
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    //下拉框查询 物料名称
    function selCxAll($event: any) {
      loading.value = true
      post({
        url: 'dwPurchase/MaterialInfo/getFieldValue',
        data: { materialName: $event },
      }).then(({ data, code }: any) => {
        loading.value = false
        if (code === 200) {
          pageData.CodeNameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 6000,
          })
        }
      })
    }

    //下拉框得到焦点 开头工艺
    const focusSel2 = () => {
      selCxAll2({ begins: '' })
    }
    //下拉数据 开头工艺
    const options2 = ref<any>(pageData.bgNameList)
    const loading2 = ref(false)
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = { begins: value, deleteState: 0 }
        loading2.value = true
        selCxAll2(ob)
        options2.value = pageData.bgNameList
        loading2.value = false
      } else {
        options2.value = []
      }
    }
    //下拉框查询 开头工艺
    function selCxAll2(val: any) {
      post({
        url: '/pdm/ProgramNumber/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          console.log(data)
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['begins'])
          })
          pageData.bgNameList = dataList
        } else {
          // Message.error({
          //     content: "查询失败！",
          //     duration: 6000,
          // });
        }
      })
    }

    //下拉框得到焦点 物料编号
    const focusSel1 = () => {
      selCxAll1({ materialCode: '', auditState: 1 })
    }
    //下拉数据 物料编号
    const options1 = ref<any>(pageData.CodeNameList)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { materialCode: value, deleteState: 0, auditState: 1 }
        loading1.value = true
        selCxAll1(ob)
        options1.value = pageData.CodeNameList
        loading1.value = false
      } else {
        options1.value = []
      }
    }
    //下拉框查询 物料编号
    function selCxAll1(val: any) {
      post({
        url: '/purchase/MaterialInfo/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.CodeNameList = data
        } else {
          // Message.error({
          //     content: "查询失败！",
          //     duration: 6000,
          // });
        }
      })
    }
    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('FormulationMaterials', () => {
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 100
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
      })
    })

    let cxbl = {}
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      materialName: '',
    })
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }
      dataForm.priorityOrNot = false
      pageData.showAdd = true
      pageData.sideTitle = '新增配方用料'
    }
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      deleteState: 0,
      obsoleteState: '',
      stepNo: 0,
      materialName: null,
      foremanTechnology: '',
      priorityOrNot: false,
      hACacidity: null,
      minValues: null,
      maxValues: null,
      stockNumber: '',
      materialCode: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          formRef.value?.validate().then((err) => {
            if (!err) {
              pageData.pageLoading = true
              if (dataForm.priorityOrNot) {
                dataForm.priorityOrNot = 1
              } else {
                dataForm.priorityOrNot = 0
              }
              if (pageData.sideTitle === '新增配方用料') {
                post({
                  url: '/pdm/formulaDose/insert',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false
                      Message.success({
                        content: '新增成功',
                        duration: 6000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 6000,
                      })
                    }
                    doRefresh()
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              } else {
                post({
                  url: '/pdm/formulaDose/update',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false
                      Message.success({
                        content: '修改成功',
                        duration: 6000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 6000,
                      })
                    }
                    //doRefresh();
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              }
            }
          })
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: '/pdm/formulaDose/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 6000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '修改失败',
                  duration: 6000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    const editHandler = (record: BrandInfo) => {
      selCxAll(record.materialName)
      //循环对象 赋值
      for (let key in record) {
        // if(key=="concentration"||key=="content"||key=="density"||key=="id"||key=="maxQuantity"||key=="minQuantity"||key=="serialNumber"||key=="wrapQuantity"){
        //     dataForm[key]=null
        // }else{
        dataForm[key] = record[key]
      }
      if (dataForm.priorityOrNot == 1) {
        dataForm.priorityOrNot = true
      } else {
        dataForm.priorityOrNot = false
      }
      pageData.sideTitle = '修改配方用料'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => { }
    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
          '<th>序号</th><th>开头工艺</th><th>物料编码</th><th>物料名称</th><th>是否优先</th><th>最小值</th><th>最大值</th><th>HAC酸性用量</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (
            gridOption.value
              .getSelectedRows()
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['id'] + '</td>'
          body +=
            '<td>' + (o['foremanTechnology'] == undefined ? '' : o['foremanTechnology']) + '</td>'
          body += '<td>' + (o['stockNumber'] == undefined ? '' : o['stockNumber']) + '</td>'
          body += '<td>' + (o['materialName'] == undefined ? '' : o['materialName']) + '</td>'
          body += '<td>' + (o['priorityOrNot'] === 0 ? ' ' : '√') + '</td>'
          body += '<td>' + (o['minValues'] == undefined ? '' : o['minValues']) + '</td>'
          body += '<td>' + (o['maxValues'] == undefined ? '' : o['maxValues']) + '</td>'
          body += '<td>' + (o['hACacidity'] == undefined ? '' : o['hACacidity']) + '</td>'
          body += '<td>' + (o['remark'] == undefined ? '' : o['remark']) + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '配方用料定义', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/pdm/formulaDose/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '配方用料定义.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/pdm/formulaDose/importModelData', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    const hacChange = () => {
      // if (
      //   dataForm.maxValues == null ||
      //   dataForm.minValues == null ||
      //   dataForm.maxValues == '' ||
      //   dataForm.minValues == ''
      // ) {
      //   dataForm.hACacidity = null
      //   Message.error('请先输入最小值和最大值！')
      //   return
      // } else {
      //   if (dataForm.hACacidity > dataForm.maxValues || dataForm.hACacidity < dataForm.minValues) {
      //     dataForm.hACacidity = null
      //     Message.warning('输入的值必须在最大值和最小值之间！')
      //     return
      //   }
      // }
    }
    const minChange = () => {
      if (
        dataForm.maxValues != null &&
        dataForm.minValues != null &&
        dataForm.minValues != '' &&
        dataForm.maxValues != ''
      ) {
        if (dataForm.minValues > dataForm.maxValues) {
          dataForm.minValues = null
          Message.warning('最小值必须小于最大值！')
          return
        }
      }
    }
    const maxChange = () => {
      if (
        dataForm.maxValues != null &&
        dataForm.minValues != null &&
        dataForm.minValues != '' &&
        dataForm.maxValues != ''
      ) {
        if (dataForm.maxValues < dataForm.minValues) {
          dataForm.maxValues = null
          Message.warning('最大值必须大于最小值！')
          return
        }
      }
    }
    const wlClick = () => {
      if (dataForm.materialCode == '') {
        Message.error('请先选择物料编号！')
        return
      }
    }
    // //设置权限
    // // ['查询', '新增', '删除', '导出', '导入']
    // const permissionStore = usePermission()

    // if (permissionStore.hasPermisson('ppzl.cx')) {

    //     pageData.btnList.push("查询")
    // }
    // if (permissionStore.hasPermisson('ppzl.xz')) {
    //     pageData.btnList.push("新增")
    // }
    // if (permissionStore.hasPermisson('ppzl.sc')) {
    //     pageData.btnList.push("删除")
    // }
    // if (permissionStore.hasPermisson('ppzl.dc')) {
    //     pageData.btnList.push("导出")
    // }
    // if (permissionStore.hasPermisson('ppzl.dr')) {
    //     pageData.btnList.push("导入")
    // }
    // if (permissionStore.hasPermisson('ppzl.xg')) {
    //     pageData.isEdit = true
    // }
    // console.log(permissionStore.hasPermisson('ppzl.cx'));
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      width:150
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('FormulationMaterials01', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    return {
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      wlClick,
      pagingList1,
      huiche,
      localeText1,
      options2,
      loading2,
      handleSearch2,
      focusSel2,
      hacChange,
      minChange,
      maxChange,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      inputBlur,
      exports,
      options,
      loading,
      downloadHandler,
      importHandler,
      options1,
      loading1,
      handleSearch1,
      focusSel1,
      headerShow,
      handleChange,
      PageSize,
      change1,
      defaultColDef,
      tc,
      gridOption,
      gridReady,
      total,
      page,
      size,
      WHService,
      wlmcFocus,
      wlChange,
      selCxAll,
    }
  },
  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>